package com.example.mobileeducationtv;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class TextMessageReceiver extends BroadcastReceiver{
	
	String sender = null;
	
	public void onReceive(Context context, Intent intent)
	{
		Bundle bundle=intent.getExtras();
		String address = null;
		String messageBody = null;
		SmsMessage[] msgs = null;
		if(bundle != null) {
			Object[] pdus = (Object[]) bundle.get("pdus");
			msgs = new SmsMessage[pdus.length];
			for(int i=0; i<msgs.length; i++) {
				msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
				if(i==0) {
					address = msgs[i].getOriginatingAddress();
				}
				messageBody = msgs[i].getMessageBody().toString();
			}
			
			Toast.makeText(context,  "New Message Received", Toast.LENGTH_LONG).show();
			this.abortBroadcast(); //Prevents other applications from receiving the message
			
			Intent broadcastMessage = new Intent();
			broadcastMessage.setAction("ReceiveSMSActivity");
			broadcastMessage.putExtra("msg", messageBody);
			broadcastMessage.putExtra("num", address);
			//Log.i("It actually gets the message here", messageBody + " and " + address);
			DatabaseHelper db = new DatabaseHelper(context);
			db.addMessage(new Messages(address, messageBody));
			context.sendBroadcast(broadcastMessage);
		}
		
	}
}
